package com.yumo.kangchenjunga.coupon;

import static org.assertj.core.api.Assertions.assertThat;

import java.time.LocalDate;
import java.time.LocalDateTime;

import javax.transaction.Transactional;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.jdbc.Sql;

import com.yumo.kangchenjunga.activity.NoSuchActivityException;
import com.yumo.kangchenjunga.coupon.v1.CouponService;
import com.yumo.kangchenjunga.coupon.v1.NoMoreAllocatedCouponException;

import cn.leafcraft.utils.webutil.datetime.DateTimeUtils;

@SpringBootTest(properties = { "spring.test.database.replace=none",
		"spring.datasource.url=jdbc:mariadb://localhost/devkit", "spring.datasource.password=secret",
		"spring.datasource.username=devkit" })
@Transactional
public class CouponServiceTests2 {

	@Autowired
	private CouponService service;
	@Autowired
	private com.yumo.kangchenjunga.coupon.v2.CouponService serviceV2;

	@Sql("CouponCustomerAllocationRepositoryTests.testSummaryByCustomerId.sql")
	@Test
	public void testGetCouponSummaryByCustomerId() {
		var result = service.getCouponSummaryByCustomerId(1);

		assertThat(result.details).hasSize(4);
	}

	@Sql
	@Test
	public void testObtainExpectSuccess() throws NoMoreAllocatedCouponException, NoSuchActivityException {
		DateTimeUtils.useFixedClockAt(LocalDateTime.of(2019, 1, 5, 12, 0));

		var result = serviceV2.obtain(1, 1);

		assertThat(result.activityId).isEqualTo(1);
		assertThat(result.couponCode).isEqualTo("12345601");
		assertThat(result.customerId).isEqualTo(1);
		assertThat(result.effectiveTime).isEqualTo(LocalDate.of(2019, 1, 5));
		assertThat(result.expirationTime).isEqualTo(LocalDate.of(2019, 1, 6));
		assertThat(result.secretCode).isEqualTo("123456");

		DateTimeUtils.useSystemDefaultZoneClock();
	}

	@Sql
	@Test
	@WithUserDetails
	public void testAllocateByCustomerLevel() throws NoSuchActivityException {
		var result = service.allocateByCustomerLevel(1, 1, 3);

		assertThat(result.couponAmount).isEqualTo(6);
		assertThat(result.couponPerCustomer).isEqualTo(3);
		assertThat(result.customerAmount).isEqualTo(2);
	}

}
